/**
 * 
 */
package com.woan.api.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * @author hero
 * 
 */
public class HttpTool {

	Logger log = Logger.getLogger(this.getClass().getName());

	/**
	 * 向目标地址发起http POST请求，并获取返回结果
	 * 
	 * @param reuquestUrl
	 *            ：目标地址
	 * @param httpData
	 *            ：需要向目标地址发送的数据
	 * @return ：目标地址的返回值
	 */
	public String sendPostHttpRequest(String reuquestUrl, String httpData) {

		StringBuffer sResult = new StringBuffer();
		//SysGlobal sg = new SysGlobal();
		try {
			//if("http://192.168.0.201:3399/notify".equals(reuquestUrl)){
			//	reuquestUrl = sg.getImgpost();
			//}
			//System.out.println(reuquestUrl);
			//System.out.println(httpData);
			URL url = new URL(reuquestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(10000);
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Length", String.valueOf(httpData
					.getBytes().length));

			PrintWriter out = null;
			out = new PrintWriter(new OutputStreamWriter(
					conn.getOutputStream(), "UTF-8"));// 此处改动
			// 发送请求
			out.print(httpData);
			out.flush();
			out.close();
			int responseCode = conn.getResponseCode();
			InputStream httpIS = null;
			java.io.BufferedReader http_reader = null;

			if (responseCode == HttpURLConnection.HTTP_OK) {
				// 发送正常
				// 读取数据
				httpIS = conn.getInputStream();
				http_reader = new java.io.BufferedReader(
						new java.io.InputStreamReader(httpIS, "UTF-8"));
				String line = null;
				while ((line = http_reader.readLine()) != null) {
					if (sResult.length() > 0) {
						sResult.append("\n");
					}
					sResult.append(line);
				}
			} else {
				sResult.append("-1");
			}

			log.info("sendHttpRequest sResult==" + sResult);

		} catch (Exception ex) {
			//System.out.println("访问请求失败：" + ex.toString());
//			log.info("访问请求失败：" + ex.toString());
			ex.printStackTrace();
		}
		return sResult.toString();
	}

	/**
	 * 向目标地址发起http GET请求，并获取返回结果
	 * 
	 * @param reuquestUrl
	 *            ：目标地址
	 * @return ：目标地址的返回值
	 */
	public String sendGetHttpRequest(String reuquestUrl) {

		StringBuffer sResult = new StringBuffer();
		String str = "";

		try {
			URL url = new URL(reuquestUrl);
			// 根据拼凑的URL，打开连接，URL.openConnection函数会根据URL的类型，
			// 返回不同的URLConnection子类的对象，这里URL是一个http，因此实际返回的是HttpURLConnection
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 进行连接，但是实际上get
			// request要在下一句的connection.getInputStream()函数中才会真正发到
			// 服务器
			conn.connect();
			// 取得输入流，并使用Reader读取
			int responseCode = conn.getResponseCode();

			InputStream httpIS = null;
			java.io.BufferedReader http_reader = null;

			if (responseCode == HttpURLConnection.HTTP_OK) {
				// 发送正常
				// 读取数据
				httpIS = conn.getInputStream();
				http_reader = new java.io.BufferedReader(
						new java.io.InputStreamReader(httpIS, "UTF-8"));
				String line = null;
				while ((line = http_reader.readLine()) != null) {
					if (sResult.length() > 0) {
						sResult.append("\n");
					}
					sResult.append(line);
				}
			} else {
				sResult.append("-1");
			}
			str = sResult.toString();
			// str = "成功";
//			log.info("sendHttpRequest sResult前==" + str);
			// str = new String(str.getBytes(), "UTF-8");

			log.info("sendHttpRequest sResult==" + str);
		} catch (Exception ex) {
			log.info("访问请求失败：" + ex.toString());
			ex.printStackTrace();
		}
		return str;
	}

	public void retData(HttpServletResponse response, String data) {

		log.info("data=====" + data);
		//System.out.println("data=====" + data);
		try {
			// 此处可以解决响应中文乱码问题
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			response.setContentType("text/plain");
			// out.println("<?xml version=1.0 encoding=UTF-8 ?>");
			out.print(data);
			out.flush();
			out.close();
		} catch (IOException ex) {
			log.info("注册失败：" + ex.toString());
			ex.printStackTrace();
		}
	}

	public Hashtable<String, String> getRequestBody(HttpServletRequest request)
			throws IOException, UnsupportedEncodingException {

		Hashtable<String, String> hash = new Hashtable<String, String>();

		final int BUFFER_SIZE = 10 * 1024;
		byte[] buffer = new byte[BUFFER_SIZE];
		ServletInputStream sis = request.getInputStream();
		int length = 0;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		do {
			length = sis.read(buffer);
			if (length > 0) {
				baos.write(buffer, 0, length);
			}
		} while (length * 2 == BUFFER_SIZE);
		// 从post请求中获取到的数据
		String bodyData = new String(baos.toByteArray(), "UTF-8");
		hash.put("postdata", bodyData);
		System.out.println("bodyData2==" + bodyData);
		String[] arrStr = bodyData.split("&");
		if (arrStr != null) {
			for (int i = 0; i < arrStr.length; i++) {
				String[] tmp = arrStr[i].split("=");
				String value = "";
				if (tmp.length > 1) {
					value = tmp[1];
				}
				hash.put(tmp[0], value);
			}
		}
		// 进行数据分解，将数据分解到
		return hash;
	}

	public static void main(String[] args) {

		// String str = "pwd=123456&verifyCode=aaa&siCode=LPWZ&username=004";
		//
		// String[] arrStr = str.split("&");
		// if (arrStr != null) {
		// for (int i = 0; i < arrStr.length; i++) {
		// String[] tmp = arrStr[i].split("=");
		// String value = "";
		// if (tmp.length > 1) {
		// value = tmp[1];
		// }
		// System.out.println(tmp[0] + "***" + value);
		// }
		// }

		//HttpTool ht = new HttpTool();
		//System.out.println(ht.sendPostHttpRequest(
		//		"http://192.168.0.201:3399/notify",
		//		"type=4&file_type=0&author=woan|test1|358059040013199&file_name=1-94c7c8c7100075bc610c34f2.jpg&private=0&vs_id=1&service_code=123456&path=./20130327/00/47/fa177138f94a7ea01f549b1aa7893d03/&hashed_id=1-94c7c8c7100075bc610c34f2"));
		//System.out.println(ht.sendPostHttpRequest(
		//		"http://192.168.0.201:3399/notify "," {service_code=TEST, private=0, file_type=0, author=admin|hzga, vs_id=1, file_name=1-a7f014da81aa2ca28efd66fa.jpg, type=4, postdata=type=4&file_type=0&author=admin|hzga&file_name=1-a7f014da81aa2ca28efd66fa.jpg&private=0&vs_id=1&service_code=TEST&path=./20120504/10/55/fa177138f94a7ea01f549b1aa7893d03/&hashed_id=1-a7f014da81aa2ca28efd66fa, hashed_id=1-a7f014da81aa2ca28efd66fa, path=./20120504/10/55/fa177138f94a7ea01f549b1aa7893d03/}"));

	}
	public static void test() {
		HttpTool ht = new HttpTool();
		System.out.println(ht.sendPostHttpRequest(
				"http://211.99.249.90/monitorapi/if_auth.xml "," type=6"));

//		System.out.println(ht.sendPostHttpRequest(
//				"http://220.181.83.189/ProvServer/if_notify.xml",
//				"hashed_id=1-7a6f10906cfa8a3c796d3c36c1491243&type=6"));
	}

}
